package com.bugpool.leilema.freamwork.datascope;

import com.bugpool.leilema.freamwork.annotation.DataScope;
import com.bugpool.leilema.freamwork.satoken.SaTokenUtil;
import com.bugpool.leilema.tc.bean.dto.DataScopeEstimateDTO;
import com.bugpool.leilema.tc.bean.vo.SysUserVo;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.session.Configuration;

import java.lang.reflect.Method;
import java.util.Optional;

/**
 * @Author wh
 * @Description 权限控制
 * @Date 2023/6/12 10:19
 * @Version 1.0
 **/
public class DataScopeUtils {

    protected static final ThreadLocal<String> threadLocal = new ThreadLocal<>();

    /**
     * 设置权限标识
     */
    public static void startDataScope() {
        threadLocal.set(DataScopeConstants.DATA_SCOPE);
    }

    /**
     * 判断是否需要数据权限增强
     *
     * @param invocation
     * @return
     */
    public static final DataScopeEstimateDTO hasDataScope(Invocation invocation) {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        String id = mappedStatement.getId();
        String className = id.substring(0, id.lastIndexOf("."));
        String methodName = id.substring(id.lastIndexOf(".") + 1);
        DataScope annotation = null;
        try {
            final Method[] methods = Class.forName(className).getMethods();
            for (Method method : methods) {
                if (method.getName().equals(methodName) && method.isAnnotationPresent(DataScope.class)) {
                    annotation = method.getAnnotation(DataScope.class);
                }
            }
            DataScopeEstimateDTO dse = new DataScopeEstimateDTO();
            if (annotation == null) {
                return dse;
            }
            dse.setHasDataScope(true);      //需要数据权限增强
            dse.setTbAlias(annotation.value());         //主表的别名
            return dse;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * 获取权限标识
     */
    public static String getDataScope() {
        return threadLocal.get();
    }

    /**
     * 清除权限标识
     */
    public static void cleanDataScope() {
        threadLocal.remove();
    }

    /**
     * 获取用户id
     */
    public static String getUserId() {
        return SaTokenUtil.getUserId();
    }

    /**
     * 获取用户名称
     */
    public static String getUserName() {
        return SaTokenUtil.getLoginName();
    }

    /**
     * 获取组织架构id
     */
    public static Long getDeptId() {
        return Optional.ofNullable(SaTokenUtil.getUser()).map(user -> user.getDeptId()).orElse(1L);
    }

    /**
     * 获取登录用户信息
     */
    public static SysUserVo getUser() {
        return SaTokenUtil.getUser();
    }

    /**
     * 判断是否是 超级管理员
     */
    public static Boolean isAdmin() {
        return Optional.ofNullable(SaTokenUtil.getUser()).map(user -> user.isAdmin()).orElse(false);
    }

}
